package bb.lanxing.activity.mine;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import com.umeng.analytics.MobclickAgent;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.RankingsOverviewAdapter;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.City;
import bb.lanxing.model.database.Province;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.json.RankTypeBean;
import bb.lanxing.mvp.presetner.ClubPresenter;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.Log;
import bb.lanxing.view.BikeHeader;
import bb.lanxing.view.sport.SportTypeSwitch;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class RankingsOverviewActivity extends BaseActivity implements ClubPresenter.IClubEventListener {
    public static final int RANK_CLUB = 1;
    public static final int RANK_PERSON = 0;
    private RankingsOverviewAdapter adapter;
    private RadioButton clubView;
    private int currentRankType;
    private ListView rankListView;
    private ImageView imageView;
    private View mTypeView;
    private TextView mainTeamEmpty;
    private RadioButton personView;
    private RadioGroup radioGroup;
    private List<RankTypeBean> rankList;
    private PtrClassicFrameLayout refreshView;
    private ScrollView scrollView;
    private LinearLayout sportRankLayout;
    private TextView tvRankStyle;
    private TextView typeView;
    private int sportType = 3;
    private int currentSportIndex = -1;
    private Handler handler = new Handler();

    private Button buttonCycling, buttonRunning, buttonHiking;
    private Button selectedButton;
    private Map<Integer, Integer> buttonToSportTypeMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rankings_overview);
        bindUIComponents(getWindow().getDecorView());
        setupActionBar(true);
        setupViews();
        initializeAdapter();
        setupAutoRefreshView();
        ClubPresenter.getInstance().registerClubEventListener(this);
    }

    private void determineRankType() {
        currentRankType = getIntent().getLongExtra("club_id", -1L) != -1 ? RANK_CLUB : SharedManager.getInstance().getRankPeopleType();
    }

    private void setupRankListVisibility() {
        boolean isPersonRank = currentRankType == RANK_PERSON;
        sportRankLayout.setVisibility(isPersonRank ? View.VISIBLE : View.GONE);
        mainTeamEmpty.setVisibility(!isPersonRank && shouldShowMainTeamEmpty() ? View.VISIBLE : View.GONE);
        personView.setChecked(isPersonRank);
        clubView.setChecked(!isPersonRank);
    }

    private boolean shouldShowMainTeamEmpty() {
        return App.getContext().getSigninUser() != null && ClubPresenter.getPrimaryClubId() == -1;
    }

    private void setupRadioGroupListener() {
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            boolean isPersonView = checkedId == R.id.personView;
            mainTeamEmpty.setVisibility(!isPersonView && shouldShowMainTeamEmpty() ? View.VISIBLE : View.GONE);
            currentRankType = isPersonView ? RANK_PERSON : RANK_CLUB;
            adapter.notifyDataSetChanged();
            if (isPersonView) {
                sportRankLayout.setVisibility(View.VISIBLE);
            } else {
                sportRankLayout.setVisibility(View.GONE);
            }
            fetchPersonRank();
            SharedManager.getInstance().setRankPeopleType(currentRankType);
        });
    }

    private void setupSportTypeButtons() {
        buttonCycling = findViewById(R.id.button_cycling);
        buttonRunning = findViewById(R.id.button_running);
        buttonHiking = findViewById(R.id.button_hiking);
        buttonCycling.setOnClickListener(v -> handleButtonClicked(buttonCycling));
        buttonRunning.setOnClickListener(v -> handleButtonClicked(buttonRunning));
        buttonHiking.setOnClickListener(v -> handleButtonClicked(buttonHiking));

        buttonToSportTypeMap = new HashMap<>();
        buttonToSportTypeMap.put(R.id.button_cycling, Workout.TYPE_CYCLING);
        buttonToSportTypeMap.put(R.id.button_running, Workout.TYPE_RUNNING);
        buttonToSportTypeMap.put(R.id.button_hiking, Workout.TYPE_WALKING);

        setSelectedButtonBySportType(sportType);
        selectButton(selectedButton);
    }

    private void setupRefreshMechanism() {
        BikeHeader bikeHeader = new BikeHeader(this);
        refreshView.setHeaderView(bikeHeader);
        refreshView.addPtrUIHandler(bikeHeader);
        refreshView.setLastUpdateTimeRelateObject(this);
        refreshView.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                fetchPersonRank();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, scrollView, header);
            }
        });
    }

    private void setupViews() {
        rankList = new ArrayList();
        setTitle("");
        determineRankType();
        setupRankListVisibility();
        setupRadioGroupListener();
        if (Province.getCount() <= 0) {
            Province.importDatas();
            City.importDatas();
        }
        sportType = SharedManager.getInstance().getMineSportType();
        currentSportIndex = sportType;
        customizeSportUI(sportType);
        setupRefreshMechanism();
        mainTeamEmpty.setOnClickListener(v -> RankingsOverviewActivity.this.setMainTeam());
        setupSportTypeButtons();
    }

    public void initializeAdapter() {
        adapter = new RankingsOverviewAdapter(this);
        rankListView.setAdapter(adapter);
        rankListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RankingsOverviewActivity.this.handleItemClick(position);
            }
        });
    }

    public void setupAutoRefreshView() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                RankingsOverviewActivity.this.refreshView.autoRefresh();
            }
        }, 100L);
    }

    public void finalizeRefreshView() {
        handler.post(() -> RankingsOverviewActivity.this.refreshView.refreshComplete());
    }

    public void handleItemClick(int index) {
        RankTypeBean rankTypeBean = this.rankList.get(index);
        //TODO
        if (this.currentRankType == RANK_CLUB) {
//            Intent intent = new Intent(this, ClubRankListDetailActivity.class);
//            int clubTimeType = rankTypeBean.getClubTimeType();
//            intent.putExtra("rank_type", clubTimeType);
//            intent.putExtra("area_id", rankTypeBean.getCityId());
//            startActivity(intent);
//            uMengEventTimeConst(rankTypeBean.getCityId(), clubTimeType);
            return;
        } else {
            Intent intent2 = new Intent(this, SportsRankDetailActivity.class);
            intent2.putExtra("time_type", rankTypeBean.getTimeType());
            intent2.putExtra("area_id", rankTypeBean.getCityId());
            intent2.putExtra("area_type", rankTypeBean.getAreaType());
            intent2.putExtra("title", rankTypeBean.getTitle());
            intent2.putExtra("sport_type", this.currentSportIndex);
            startActivity(intent2);
            logUMengEvent(rankTypeBean.getCityId(), rankTypeBean.getTimeType());
        }
    }


    public void fetchPersonRank() {
        Call requestClubRank;
        if (this.currentRankType == RANK_PERSON) {
            requestClubRank = MyHttpClient.requestPersonRank(this.currentSportIndex);
        } else {
            requestClubRank = MyHttpClient.requestClubRank();
        }
        Observable.create(new NetSubscribe(requestClubRank))
                  .subscribeOn(Schedulers.io())
                  .flatMap(new Func1<String, Observable<List<RankTypeBean>>>() {
                      @Override
                      public Observable<List<RankTypeBean>> call(String s) {
                          ArrayList arrayList = new ArrayList();
                          try {
                              JSONArray jSONArray = new JSONObject(s).getJSONArray("data");
                              for (int i = 0; i < jSONArray.length(); i++) {
                                  arrayList.add(new RankTypeBean(jSONArray.getJSONObject(i)));
                              }
                          } catch (JSONException e) {
                              e.printStackTrace();
                          }
                          return Observable.just(arrayList);
                      }
                  })
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe((Subscriber) new Subscriber<List<RankTypeBean>>() {
                      @Override
                      public void onCompleted() {
                          RankingsOverviewActivity.this.finalizeRefreshView();
                      }

                      @Override
                      public void onError(Throwable e) {
                          RankingsOverviewActivity.this.finalizeRefreshView();
                      }

                      @Override
                      public void onNext(List<RankTypeBean> rankTypeBean) {
                          Log.d("RankingsOverviewActivity", "onNext: ");
                          RankingsOverviewActivity.this.finalizeRefreshView();
                          RankingsOverviewActivity.this.rankList.clear();
                          RankingsOverviewActivity.this.rankList.addAll(rankTypeBean);
                          RankingsOverviewActivity.this.adapter.setRankItems(rankTypeBean);
                          RankingsOverviewActivity.this.adapter.notifyDataSetChanged();
                      }
                  });
    }

    private void displaySportTypePopup(View v) {
        SportTypeSwitch sportTypeSwitch = new SportTypeSwitch(this, this.sportType, 4);
        sportTypeSwitch.setOnSportTypeSwitchListener(new SportTypeSwitch.OnSportTypeSwitchListener() {
            @Override
            public void onSwitch(int sportType) {
                RankingsOverviewActivity.this.updateSportType(sportType);
            }
        });
        sportTypeSwitch.showAsDropDown(v);
    }

    private void bindUIComponents(View bindSource) {
        this.radioGroup = (RadioGroup) bindSource.findViewById(R.id.radio_group);
        this.personView = (RadioButton) bindSource.findViewById(R.id.personView);
        this.clubView = (RadioButton) bindSource.findViewById(R.id.clubView);
        this.tvRankStyle = (TextView) bindSource.findViewById(R.id.tvRankStyle);
        this.typeView = (TextView) bindSource.findViewById(R.id.typeView);
        this.imageView = (ImageView) bindSource.findViewById(R.id.imageView);
        this.rankListView = (ListView) bindSource.findViewById(R.id.rank_list_view);
        this.sportRankLayout = bindSource.findViewById(R.id.sportRankLayout);
        this.refreshView = (PtrClassicFrameLayout) bindSource.findViewById(R.id.refreshView);
        this.scrollView = (ScrollView) bindSource.findViewById(R.id.scrollView);
        this.mainTeamEmpty = (TextView) bindSource.findViewById(R.id.tv_setup_main_club);
        this.mTypeView = bindSource.findViewById(R.id.typeView);
        mTypeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                displaySportTypePopup(view);
            }
        });
    }

    private void handleButtonClicked(Button button) {
        selectButton(button);
        updateSportType(buttonToSportTypeMap.get(button.getId()));
    }

    private void selectButton(Button button) {
        if (selectedButton != null && selectedButton != button) {
            selectedButton.setBackgroundTintList(getResources().getColorStateList(R.color.rank_sport_button_default));
            selectedButton.setTextColor(getResources().getColor(R.color.rank_sport_text_default));
        }
        button.setBackgroundTintList(getResources().getColorStateList(R.color.black));
        button.setTextColor(getResources().getColor(R.color.rank_sport_text_selected));
        selectedButton = button;
    }

    private void setSelectedButtonBySportType(int sportType) {
        switch (sportType) {
            case Workout.TYPE_WALKING:
                selectedButton = buttonHiking;
                break;
            case Workout.TYPE_RUNNING:
                selectedButton = buttonRunning;
                break;
            case Workout.TYPE_CYCLING:
                selectedButton = buttonCycling;
                break;
        }
    }

    public void updateSportType(int sportType) {
        this.sportType = sportType;
        this.currentSportIndex = sportType;
        SharedManager.getInstance().setMineSportType(sportType);
        customizeSportUI(sportType);
        fetchPersonRank();
    }

    private void customizeSportUI(int sportType) {
        if (sportType == Workout.TYPE_WALKING) {
            this.tvRankStyle.setText(getString(R.string.ranking_sport_walking));
        } else if (sportType == Workout.TYPE_RUNNING) {
            this.tvRankStyle.setText(getString(R.string.ranking_sport_running));
        } else {
            this.tvRankStyle.setText(getString(R.string.ranking_sport_cycling));
        }
    }

    public void setMainTeam() {
//        startActivity(new Intent(this, MainClubActivity.class));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ClubPresenter.unregisterClubEventListener(this);
    }

    @Override
    public boolean onClubEvent(int id, long clubId, Object data) {
        if (id != 17) {
            return false;
        }
        this.mainTeamEmpty.setVisibility(View.GONE);
        return false;
    }

    public void logUMengEvent(int area, int time) {
        if (this.currentRankType == 1) {
            if (time == 3) {
                if (area == 0) {
                    MobclickAgent.onEventValue(this, UmengEventConst.CLUB_RANK_NATION_YEAR, null, 1);
                } else {
                    MobclickAgent.onEventValue(this, UmengEventConst.CLUB_RANK_LOCAL_YEAR, null, 1);
                }
            } else if (time != 4) {
            } else {
                if (area == 0) {
                    MobclickAgent.onEventValue(this, UmengEventConst.CLUB_RANK_NATION_MONTH, null, 1);
                } else {
                    MobclickAgent.onEventValue(this, UmengEventConst.CLUB_RANK_LOCAL_MONTH, null, 1);
                }
            }
        } else if (time == 2) {
            if (area == 0) {
                MobclickAgent.onEventValue(this, UmengEventConst.PROPLR_RANK_NATION_YEAR, null, 1);
            } else {
                MobclickAgent.onEventValue(this, UmengEventConst.PROPLR_RANK_LOCAL_YEAR, null, 1);
            }
        } else if (time != 3) {
        } else {
            if (area == 0) {
                MobclickAgent.onEventValue(this, UmengEventConst.PROPLR_RANK_NATION_MONTH, null, 1);
            } else {
                MobclickAgent.onEventValue(this, UmengEventConst.PROPLR_RANK_LOCAL_MONTH, null, 1);
            }
        }
    }
}
